package com.thx.role.service;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thx.common.datasource.DataSource;
import com.thx.common.service.BaseManager;
import com.thx.common.spring.BeanFactory;
import com.thx.role.dao.RoleDao;
import com.thx.role.model.Role;
import com.thx.user.model.User;
import com.thx.user.service.UserManager;

@Service
@DataSource("dataSourceB")
@Transactional(readOnly = true)
public class RoleManager extends BaseManager<Role> {
	
	@Autowired
	private RoleDao roleDao;

	public List<Role> searchRole(String roleName) {
		// TODO Auto-generated method stub
		return roleDao.searchRole(roleName);
	}

	public List<Role> searchAllRoles(String roleName) {
		return roleDao.searchAllRoles(roleName);
	}

	public Role findByName(String roleName) {

		return roleDao.findByRoleName(roleName);
	}
	
	public List<Role> findByUserId(String userId) {
		
		return roleDao.findByUserId(userId);
	}

	@Transactional(readOnly = false)
	public void delStatus(Object... ids) {
		if (ids != null && ids.length > 0) {
			if (ids[0] instanceof String) {
				for (Object id : ids) {
					Role role = this.get((String) id);
					Set<User> users = role.getUsers();
					for(User user: users){
						user.getRoles().remove(role);
						UserManager userMgr = (UserManager)BeanFactory.getBean("userManager");
						userMgr.save(user);
					}
					role.setStatus("0");
					save(role);
				}

			} else if (ids[0] instanceof Long) {
				for (Object id : ids) {
					Role role = this.get((Long) id);
					Set<User> users = role.getUsers();
					for(User user: users){
						user.getRoles().remove(role);
						UserManager userMgr = (UserManager)BeanFactory.getBean("userManager");
						userMgr.save(user);
					}
					role.setStatus("0");
					save(role);
				}
			}
		}
	}
}
